/*********************************************************************************
 * Copyright (c) 2006 Forschungszentrum Juelich GmbH 
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 
 * (1) Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the disclaimer at the end. Redistributions in
 * binary form must reproduce the above copyright notice, this list of
 * conditions and the following disclaimer in the documentation and/or other
 * materials provided with the distribution.
 * 
 * (2) Neither the name of Forschungszentrum Juelich GmbH nor the names of its 
 * contributors may be used to endorse or promote products derived from this 
 * software without specific prior written permission.
 * 
 * DISCLAIMER
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 ********************************************************************************/
package pl.umk.mat.fred.unicore.urc.storagemanagement.views.cellEditors;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.apache.commons.httpclient.util.URIUtil;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.viewers.DialogCellEditor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.dialogs.ISelectionStatusValidator;
import org.unigrids.services.atomic.types.GridFileType;

import pl.umk.mat.fred.unicore.urc.storagemanagement.dialogs.ServiceSelectionDialog;
import pl.umk.mat.fred.unicore.urc.storagemanagement.tree.nodes.FileNode;

import com.intel.gpe.clients.impl.transfers.U6ProtocolConstants;
import com.intel.gpe.gridbeans.parameters.IFileParameterValue;

import de.fzj.unicore.rcp.gpe4eclipse.GPEActivator;
import de.fzj.unicore.rcp.servicebrowser.nodes.AbstractFileNode;

/**
 * @author demuth
 * 
 */
public class StageInTypeU6StorageCellEditor extends DialogCellEditor {

	private class SelectionValidator implements ISelectionStatusValidator {

		@Override
		public IStatus validate(Object[] selection) {
			if ((selection == null) || (selection.length == 0)) {
				return new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, IStatus.ERROR,
						"No file selected.", null);
			}
			for (Object o : selection) {
				if (!(o instanceof FileNode)) {
					return new Status(IStatus.ERROR, PlatformUI.PLUGIN_ID, IStatus.ERROR,
							"Select only files.", null);
				}
			}
			
			return new Status(IStatus.OK, PlatformUI.PLUGIN_ID, IStatus.OK, "", null);
		}
		
	}
	
	protected IFileParameterValue file;
	protected boolean multiFileSelector = false;

	/**
	 * The label that gets reused by <code>updateLabel</code>.
	 */
	private Label defaultLabel;

	/** A CellEditor, opening a FileBrowser for selecting a File */
	public StageInTypeU6StorageCellEditor(Composite parent) {
		this(parent, false);
	}

	public StageInTypeU6StorageCellEditor(Composite parent,
			boolean multiFileSelector) {
		super(parent);
		this.multiFileSelector = multiFileSelector;
	}

	@Override
	protected Control createContents(Composite cell) {
		defaultLabel = new Label(cell, SWT.LEFT);
		defaultLabel.setFont(cell.getFont());
		defaultLabel.setBackground(cell.getBackground());
		return defaultLabel;
	}

	@Override
	protected void doSetValue(Object value) {

		if (!(value instanceof IFileParameterValue[])) {
			IFileParameterValue file = (IFileParameterValue) value;
			value = new IFileParameterValue[] { file };
			super.doSetValue(value);
			updateContents(file.getSource().getInternalString());
		} else {
			super.doSetValue(value);
		}
	}

	public boolean isMultiFileSelector() {
		return multiFileSelector;
	}

	@Override
	protected Object openDialogBox(Control cellEditorWindow) {
		FileNode fileNode = null;
		ServiceSelectionDialog serviceSelectionDialog = new ServiceSelectionDialog();
		try {
			file = ((IFileParameterValue[]) this.getValue())[0];

			serviceSelectionDialog.setTitle("Please select a file.");
			serviceSelectionDialog.setAllowMultiple(multiFileSelector);
			serviceSelectionDialog.setValidator(new SelectionValidator());
			serviceSelectionDialog.open();
			Object[] selected = serviceSelectionDialog.getResult();
			if (selected == null || selected.length == 0) {
				return null;
			}
			List<IFileParameterValue> result = new ArrayList<IFileParameterValue>(
					selected.length);
			for (Object n : selected) {	
				fileNode = (FileNode) n;
				IFileParameterValue current = file.clone();
				String parentDir = fileNode.getStorage().getUrl();
				if (!parentDir.endsWith("#")) {
					parentDir += "#";
				}
				current.getSource().setParentDirAddress(parentDir);
				
				String relative = fileNode.getPath();
				relative = URIUtil.encode(relative,
						org.apache.commons.httpclient.URI.allowed_fragment);
				current.getSource().setRelativePath(relative);
				
				String displayed = fileNode.getStorage().getName() + relative;
				current.getSource().setDisplayedString(displayed);
				boolean usingWildcards = current.getSource().getRelativePath()
						.contains("*");
				current.getSource().setUsingWildcards(usingWildcards);
				current.getSource().setProtocol(
						U6ProtocolConstants.UNICORE_SMS_PROTOCOL);
				String nameInWorkingDir = current.getTarget().getRelativePath();
				if (selected.length > 1 || nameInWorkingDir == null
						|| nameInWorkingDir.trim().length() == 0) {
					int cut = relative.lastIndexOf("/");
					String fileName = relative.substring(cut + 1);
					current.getTarget().setRelativePath(fileName);
					current.getTarget().setDisplayedString(fileName);
				}

				if (selected.length > 0) {
					// use a different UUID for the newly created file transfer
					String uuid = UUID.randomUUID().toString();
					current.setUniqueId(uuid);
				}
				result.add(current);
			}
			return result.toArray(new IFileParameterValue[result.size()]);
		} catch (Exception e) {
			GPEActivator.log(IStatus.WARNING,
					"Could not apply value to table entry", e);
			return file;
		} finally {
			//serviceSelectionDialog.disposeNodes();
		}
	}

	public void setMultiFileSelector(boolean filesetsAllowed) {
		this.multiFileSelector = filesetsAllowed;
	}

	@Override
	protected void updateContents(Object value) {
		if (defaultLabel == null) {
			return;
		}

		String text = "";//$NON-NLS-1$
		if (value != null) {
			text = ((IFileParameterValue[]) getValue())[0].getSource()
					.getDisplayedString();
		}
		defaultLabel.setText(text);
	}

}
